package top.infopub.job.bpa.service.impl;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.job.bpa.dao.IncaeSureDao;
import top.infopub.job.bpa.dao.OutcaeSureDao;
import top.infopub.job.bpa.dao.ProSettleDao;
import top.infopub.job.bpa.domain.GrossProfitDomain;
import top.infopub.job.bpa.service.OutcaeSureService;
import top.infopub.job.util.ParserUtil;
import top.infopub.model.bpa.OutcaeSure;

import com.google.common.collect.Maps;


@Service
public class OutcaeSureServiceImpl extends GenericServiceImpl<OutcaeSure, String> implements OutcaeSureService {

    @Autowired
    private OutcaeSureDao outcaeSureDao;

    @Autowired
    private IncaeSureDao incaeSureDao;

    @Autowired
    private ProSettleDao proSettleDao;

    @Override
    public GenericDao<OutcaeSure, String> getDao() {
        return outcaeSureDao;
    }

    @Override
    public BigDecimal selectProQaOfOutSure(Map<String, Object> where) {
        BigDecimal rs = outcaeSureDao.selectProQaOfOutSure(where);
        if (rs == null) {
            return BigDecimal.ZERO;
        }
        return rs;
    }

    @Override
    public BigDecimal selectAreaQaOfOutSure(Map<String, Object> where) {
        return outcaeSureDao.selectAreaQaOfOutSure(where);
    }

    @Override
    public BigDecimal selectAllProQaOfOutSure(Map<String, Object> where) {
        return outcaeSureDao.selectAllProQaOfOutSure(where);
    }

    @Override
    public BigDecimal selectProQaOfGrossProfit(Map<String, Object> where) {
        // 查询某个项目 建安毛利 -- 子项的 当月对外确权金额（下浮前） 对外下浮率 子项名称 
        List<GrossProfitDomain> grossProfitDomainList = outcaeSureDao.selectProQaOfGrossProfit(where);
        for (GrossProfitDomain var : grossProfitDomainList) {
            // 其中： 对内下浮率如下 
            // 1. 带入项目【分包合同】（可能需查多个合同）子项对应{对内下浮率}
            // 2. 带入项目【内部协议】子项对应{对内下浮率}
            // 3. 若无对应子项，为0
            Map<String, Object> subpackCotWhere = Maps.newHashMap();
            subpackCotWhere.put("proCode", var.getProCode());
            subpackCotWhere.put("subName", var.getSubName());
            // 查询项目【分包合同】 子项对应{对内下浮率}
            BigDecimal rateFromSubpackCot = outcaeSureDao.selectRateFromSubpackCot(subpackCotWhere);
            if (null == rateFromSubpackCot) {
                Map<String, Object> innerAgrtWhere = Maps.newHashMap();
                innerAgrtWhere.put("proCode", var.getProCode());
                innerAgrtWhere.put("subName", var.getSubName());
                // 查询项目【内部协议】子项对应{对内下浮率}
                BigDecimal rateFromInnerAgrt = outcaeSureDao.selectRateFromInnerAgrt(innerAgrtWhere);
                if (null == rateFromInnerAgrt) {
                    var.setInDownRate(BigDecimal.ZERO);
                }
                else {
                    var.setInDownRate(rateFromInnerAgrt);
                }
            }
            else {
                var.setInDownRate(rateFromSubpackCot);
            }
            // 子项 当月对内确权金额（元）（下浮前） proCode，subName
            Map<String, Object> preAmountOfSubWhere = Maps.newHashMap();
            preAmountOfSubWhere.put("proCode", var.getProCode());
            preAmountOfSubWhere.put("subName", var.getSubName());
            BigDecimal monthPreAmountOfSub = incaeSureDao.selectMonthPreAmountOfSub(preAmountOfSubWhere);
            // 取min（  对外建安产值确权表_当月对外确权金额（下浮前）、对内建安产值确权表_当月对内确权金额（下浮前） ）
            var.setMinOf(var.getMonthPreAmount().min(monthPreAmountOfSub));
        }
        // 2020-3-18修改前公式：  建安毛利：商务-【对外建安产值确权表】子项合计（{当月对外确权金额（下浮前）}*（{对外下浮率}-{对内下浮率}））

        // 2020-3-18修改后公式 --> 建安毛利：子项合计【Min（对外建安产值确权表_当月对外确权金额（下浮前）、对内建安产值确权表_当月对内确权金额（下浮前））*（对外建安产值确权表_对外下浮率—对外建安产值确权表_对内下浮率）】+{预（结）算审批表_建安毛利调整额}
        // *  (*确权表统计时间：确权月份；调整额统计时间：预(结)算审批表审批通过时间；原始单位：元）；
        BigDecimal sum = BigDecimal.ZERO;
        for (GrossProfitDomain var : grossProfitDomainList) {
            BigDecimal temp = var.getMinOf().multiply(
                (var.getOutDownRate().subtract(var.getInDownRate())).divide(ParserUtil.HUNDRED));
            sum = sum.add(temp);
        }
        Map<String, Object> grossWhere = Maps.newHashMap();
        Date begin = (Date)where.get("sureMonth");
        grossWhere.put("proCode", where.get("proCode"));
        grossWhere.put("endTimeQueryBegin", begin);
        grossWhere.put("endTimeQueryEnd", DateUtils.addMonths(begin, 1));
        // + 建安毛利调整额
        sum = sum.add(proSettleDao.selectCaeGrossAdjust(grossWhere));
        return sum.setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public int count(String proCode) {
        return outcaeSureDao.count(proCode);
    }

    @Override
    public BigDecimal selectProQaOfOutSureBefore(Map<String, Object> where) {
        BigDecimal rs = outcaeSureDao.selectProQaOfOutSureBefore(where);
        if (rs == null) {
            return BigDecimal.ZERO;
        }
        return rs;
    }

}